// pages/login/login.js
Page({
  data: {
    username: '',
    password: '',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    baseUrl: 'http://localhost:3000'
  },

  handleInput: function(e) {
    const { field } = e.currentTarget.dataset;
    const value = e.detail.value;
    
    this.setData({
      [field]: value
    });
  },

  handleLogin: function() {
    const { username, password } = this.data;
    
    if (!username || !password) {
      wx.showToast({
        title: '请输入用户名和密码',
        icon: 'none'
      });
      return;
    }

    wx.showLoading({
      title: '登录中...'
    });

    // 先获取用户信息
    wx.request({
      url: `${this.data.baseUrl}/api/login`,
      method: 'POST',
      data: {
        username,
        password
      },
      success: (res) => {
        if (res.data.success) {
          const userInfo = res.data.user;
          // 确保 userInfo 包含 role 字段
          console.log('Received user info:', userInfo);

          // 保存用户信息到本地存储
          wx.setStorageSync('userInfo', userInfo);

          this.setData({
            userInfo,
            hasUserInfo: true
          });

          wx.hideLoading();
          wx.showToast({
            title: '登录成功',
            icon: 'success',
            duration: 1500
          });

          // 延迟跳转到岗位页面
          setTimeout(() => {
            wx.switchTab({
              url: '/pages/jobs/jobs'
            });
          }, 1500);
        } else {
          wx.hideLoading();
          wx.showToast({
            title: res.data.message || '登录失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('登录失败:', err);
        wx.hideLoading();
        wx.showToast({
          title: '登录失败，请检查网络',
          icon: 'none'
        });
      }
    });
  }
});